package com.fofia.iotweb.framework.auth;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.StaticLog;
import com.fofia.iotweb.Contants.CacheContant;
import com.fofia.iotweb.common.SecureHelper;
import com.fofia.iotweb.framework.core.RequestHelper;
import org.noear.solon.Solon;
import org.noear.solon.annotation.Bean;
import org.noear.solon.annotation.Inject;
import org.noear.solon.auth.AuthProcessor;
import org.noear.solon.auth.annotation.Logical;
import org.noear.solon.core.handle.Context;

import java.util.ArrayList;
import java.util.List;


public class AuthProcessorImpl implements AuthProcessor {

    @Override
    public boolean verifyIp(String ip) {
        return true;
    }

    @Override
    public boolean verifyLogined() {
        boolean pass=validateTokenTime();
        if(!pass){
            return false;
        }
        return true;
    }

    @Override
    public boolean verifyPath(String path, String method) {
        return true;
    }

    @Override
    public boolean verifyPermissions(String[] permissions, Logical logical) {


        String permissionsStr=ArrayUtil.join(permissions,",");

        //StaticLog.info(permissionsStr);
        if("#".equals(permissionsStr)){
            return true;
        }
        //List<String> permissionList=new ArrayList<>();
       // permissionList.add("admin.self.password");
        return true;
    }

    @Override
    public boolean verifyRoles(String[] roles, Logical logical) {
        return true;
    }


    /**
     * 获取token
     * @return
     */
    public String getToken(){
        Context solonContext= Context.current();

        String token= solonContext.header("auth_token");
        if(!StrUtil.isEmpty(token)){
            return token.trim();
        }
        token=solonContext.cookieOrDefault("auth_token","");
        if(!StrUtil.isEmpty(token)){
            return token.trim();
        }
        return "";
    }

    /**
     * 验证token过期
     * @param
     * @return
     */
    private boolean validateTokenTime(){
        String token=getToken();

        if(StrUtil.isEmpty(token)){
            return false;
        }

        if("fofiaiot_admin".equals(token)){
            return true;
        }
        if(token.length()<50){
            return false;
        }
        String tokenInfo= SecureHelper.dencryptDes(token);
        //StaticLog.info("tokenInfo:{}",tokenInfo);
        String tokenTime=StrUtil.splitToArray(tokenInfo,";")[2];
        long minDiff = DateUtil.between(DateUtil.parse(tokenTime),DateUtil.date(), DateUnit.MINUTE);
        //StaticLog.info("token minDiff:{}",minDiff);
        int expire= CacheContant.cookieExpire/60;
        if(minDiff > expire){
            Context.current().cookieSet("auth_token",null,0);
            return false;
        }
        return true;
    }
}
